Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

Solution:

  1. public class Solution {
  2. public List<String> summaryRanges(int[] a) {
  3. List<String> res = new ArrayList<String>();
  4. if (a == null)
  5. return res;
  6. int i = 0, n = a.length;
  7. for (int j = 1; j < n; j++) {
  8. if ((long)a[j] - (long)a[j - 1] > 1) {
  9. // found a range
  10. res.add(getRange(a[i], a[j - 1]));
  11. i = j;
  12. }
  13. }
  14. // do a final check
  15. if (i < n)
  16. res.add(getRange(a[i], a[n - 1]));
  17. return res;
  18. }
  19. String getRange(int n1, int n2) {
  20. return (n1 == n2) ? String.valueOf(n1) : String.format("%d->%d", n1, n2);
  21. }
  22. }